import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
import GeneratePDF as gp
import os
import datetime


class CollectResults(tk.Toplevel):
    def __init__(self, parent, bag_path):
        tk.Toplevel.__init__(self, parent)
        self.title("Export Results")

        self.folder_path = os.path.dirname(bag_path)
        self.date_data = {}
        self.file_checkboxes = []
        self.dates = ""

        self.start_label = ttk.Label(self, text="start date:")
        self.start_label.grid(row=0, column=0, padx=5, pady=5, sticky="e")
        self.start_combobox = ttk.Combobox(self, values=self.dates, state="disabled")
        self.start_combobox.grid(row=0, column=1, padx=5, pady=5)
        self.start_combobox.bind("<<ComboboxSelected>>", self.OnStartSelected)
        self.end_label = ttk.Label(self, text="end date:")
        self.end_label.grid(row=1, column=0, padx=5, pady=5, sticky="e")
        self.end_combobox = ttk.Combobox(self, values=self.dates, state="disabled")
        self.end_combobox.grid(row=1, column=1, padx=5, pady=5)
        self.end_combobox.bind("<<ComboboxSelected>>", self.OnEndSelected)
        self.confirm_button = ttk.Button(
            self, text="confirm", command=self.ConfirmSelection
        )
        self.confirm_button.grid(row=2, column=0, columnspan=1, padx=5, pady=5)
        self.selectall_button = ttk.Button(
            self, text="Select All", command=self.SelectAll
        )
        self.selectall_button.grid(row=2, column=1, padx=5, pady=5)
        self.scrollbar = ttk.Scrollbar(self, orient="vertical")
        self.scrollbar.grid(row=3, column=2, sticky="ns")

        self.canvas = tk.Canvas(self, yscrollcommand=self.scrollbar.set)

        self.canvas.config(width=600, height=200)

        self.scrollbar.config(command=self.canvas.yview)
        self.canvas.grid(row=3, column=0, columnspan=2, padx=5, pady=5)
        self.GetAllJSON(self.folder_path)
        self.canvas.bind("<Configure>", lambda x: self.OnCanvasConfigure(x))
        self.bind("<KeyPress>", lambda x: self.OnKeyPress(x))

        self.menu_bar = tk.Menu(self)
        self.file_menu = tk.Menu(self.menu_bar, tearoff=0)
        self.file_menu.add_command(label="Open", command=self.OpenFolder)

    def OnCanvasConfigure(self, event):
        self.canvas.configure(scrollregion=self.canvas.bbox("all"))

    def CreateFileCheckboxes(self):
        for check_box, var in self.file_checkboxes:
            check_box.destroy()
        self.file_checkboxes = []
        count = 0
        start_time = self.start_combobox.get()
        end_time = self.end_combobox.get()
        self.frame = ttk.Frame(self.canvas)
        self.canvas.create_window((0, 0), window=self.frame, anchor="nw")

        for date, data in self.date_data.items():
            if date < start_time or date > end_time:
                continue
            for d in data:
                var = tk.BooleanVar(value=True)
                bag_file = d.get("bag", "")
                bag_file = os.path.basename(bag_file)
                checkbox = ttk.Checkbutton(self.frame, text=bag_file, variable=var)
                checkbox.grid(row=count // 2, column=count % 2)
                self.file_checkboxes.append((checkbox, var))
                count += 1
        self.canvas.configure(scrollregion=self.canvas.bbox("all"))

    def GetAllJSON(self, input_dir):
        if len(input_dir) == 0 or os.path.exists(input_dir) == False:
            self.start_combobox.config(values=[])
            self.end_combobox.config(values=[])
            self.start_combobox.config(state="disabled")
            self.end_combobox.config(state="disabled")
            return
        self.date_data = gp.GetAllJson(input_dir)
        self.dates = list(self.date_data.keys())
        self.dates.sort()
        earliest_date = self.dates[0]
        self.start_combobox.config(values=self.dates, state="readonly")
        self.start_combobox.set(earliest_date)
        lastest_date = self.dates[-1]
        end_dates = [date for date in self.dates if date >= earliest_date]
        self.end_combobox.config(values=end_dates, state="readonly")
        self.end_combobox.set(lastest_date)
        self.CreateFileCheckboxes()

    def OnStartSelected(self, event):
        if len(self.dates) == 0:
            return
        self.date = self.start_combobox.get()
        end_date = self.end_combobox.get()
        if self.date > end_date:
            self.end_combobox.set(self.date)
        end_dates = [date for date in self.dates if date >= self.date]
        self.end_combobox.config(values=end_dates)
        self.end_combobox.config(state="readonly")
        self.CreateFileCheckboxes()

    def OnEndSelected(self, event):
        self.CreateFileCheckboxes()

    def OnKeyPress(self, event):
        if event.keysym == "Return":
            self.ConfirmSelection()

    def ConfirmSelection(self):
        export_files = []
        out_date_data = {}
        for file_checkbox, var in self.file_checkboxes:
            if var.get() == True:
                export_files.append(file_checkbox.cget("text"))
                continue
        for date, data in self.date_data.items():
            out_date_data[date] = []
            for d in data:
                bag_file = d.get("bag", "")
                bag_file = os.path.basename(bag_file)
                if bag_file in export_files:
                    out_date_data[date].append(d)
        cur_date = datetime.datetime.now().strftime("%Y-%m-%d-%H")
        default_file = f"{cur_date}-exports.pdf"
        default_folder = os.path.dirname(self.folder_path)
        output_file = filedialog.asksaveasfilename(
            defaultextension=".pdf",
            filetypes=[("PDF files", "*.pdf")],
            initialfile=default_file,
            initialdir=default_folder,
        )
        if output_file:
            gp.GenerateLatexPDF(out_date_data, output_file)
        self.destroy()

    def OpenFolder(self):
        self.folder_path = filedialog.askdirectory()
        self.GetAllJSON(self.folder_path)

    def SelectAll(self):
        isAllset = True
        for file_checkbox, var in self.file_checkboxes:
            if var.get() == False:
                isAllset = False
                break
        for file_checkbox, var in self.file_checkboxes:
            var.set(not isAllset)
